<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>{{ id? '编辑企业' : '添加企业' }}</span>
      </div>
      <div class="right">
        黑马程序员
      </div>
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="ruleForm" label-width="100px" :rules="addRules" :model="addForm">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option v-for="item in industryList" :key="item.industryCode" :value="item.industryCode" :label="item.industryName" />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
              <el-upload
                class="upload-demo"
                action="#"

                :file-list="fileList"
                :http-request="httpRequest"
                :before-upload="beforeUploadFn"
                :on-remove="removeFn"
                list-type="picture"
                :limit="1"
                :on-exceed="exceedFn"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">支持扩展名为: .png, .jpg, .jpeg, 文件大小不得超过5M</div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button>重置</el-button>
        <el-button type="primary" @click="confirmSubmit">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
// , updateEnterpriseAPI
import { getIndustryListAPI, uploadLicenseAPI, createEnterpriseAPI, getEnterpriseDetailAPI, updateEnterpriseAPI } from '@/apis/enterprise'
import { validMobile } from '@/utils/validate'

export default {
  data() {
    return {
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系人电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      industryList: [], // 行业列表
      fileList: [], // 营业执照列表
      addRules: {
        name: [
          { required: true, message: '企业名称为必填', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '法人为必填', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '注册地址为必填', trigger: 'blur' }
        ],
        industryCode: [
          { required: true, message: '所在行业为必填', trigger: 'change' }
        ],
        contact: [
          { required: true, message: '企业联系人为必填', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '企业联系人电话为必填', trigger: 'blur' },
          { validator: validMobile }
        ],
        businessLicenseId: [
          { required: true, message: '请上传营业执照', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 编辑
    id() {
      return this.$route.query.id
    }
  },
  mounted() {
    // this.getIndustryList()
    // 有合同id 调用详情接口
    if (this.id) {
      this.getEnterpriseDetail()
    }
  },
  //   获取行业列表
  async created() {
    const res = await getIndustryListAPI()
    this.industryList = res.data
  },
  methods: {

    // 上传文件的过程
    async httpRequest(config) {
      // 文件 -》 FromData 实例数据对象中 -》axios 中给后台
      // 实例化 FromData 表单流数据对象容器
      const fd = new FormData()
      // 往容器里加参数名和值
      fd.append('file', config.file)
      fd.append('type', 'businessLicense')
      const res = await uploadLicenseAPI(fd)

      // 需要手动给营业执照表单域关联的id（主要）和 url 赋值
      this.addForm.businessLicenseId = res.data.id
      this.addForm.businessLicenseUrl = res.data.url

      // 赋完值，手动单独校验一次营业执照的表单域
      this.$refs.ruleForm.validateField('businessLicenseId')
      console.log(res)

      this.fileList.push({
        name: config.file.name, // 文件本身名字
        url: res.data.url // 上传成功后图片在服务器上的地址
      })
    },
    // 上传文件到服务器之前的判断
    beforeUploadFn(file) {
      // file：本地上传到浏览器文件对象
      console.log(file)

      const isAllowFileTypeList = ['image/jpeg', 'image/jpg', 'image/png']
      if (!isAllowFileTypeList.includes(file.type)) {
        // 不符合
        this.$message.error('只能上传 .png, .jpg, .jpeg 格式的营业执照图片')
        return false
      }

      const isAllow5M = file.size / 1024 / 1024
      if (isAllow5M > 5) {
        this.$message.error('文件大小只能是5Mb以内')

        // 通过 2 个判断，继续上传
        return true
      }
    },
    // 手动校验内容
    confirmSubmit() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (this.id) {
          // 编辑
            await updateEnterpriseAPI({
              ...this.addForm,
              id: this.id
            })
            this.$message.success('更新成功')
          } else {
          // 调用接口
            await createEnterpriseAPI(this.addForm)
            this.$message.success('新增成功')
          }
          // 返回列表页
          this.$router.back()
          this.fileList = []
        }
      })

      // this.$refs.ruleForm.validate(async valid => {
      //   // console.log(valid)
      //   if (valid) {
      //     const res = await createEnterpriseAPI(this.addForm)
      //     console.log(res)
      //     this.$refs.ruleForm.resetFields()
      //     this.$router.back()
      //     this.fileList = []
      //   }
      // })
    },
    // 编辑回显
    async getEnterpriseDetail() {
      const res = await getEnterpriseDetailAPI(this.id)
      console.log(res)
      const { name, legalPerson, registeredAddress, industryCode, contact, contactNumber, businessLicenseUrl, businessLicenseId } = res.data
      this.addForm = { name, legalPerson, registeredAddress, industryCode, contact, contactNumber, businessLicenseUrl, businessLicenseId }
      this.fileList = [{
        name: res.data.businessLicenseName,
        url: businessLicenseUrl
      }]
    },

    // 文件列表一处时钩子函数
    removeFn(file, fileList) {
      this.fileList = fileList

      this.addForm.businessLicenseUrl = ''
      this.addForm.businessLicenseId = ''
    },
    // 超出文件上传的钩子
    exceedFn() {
      this.$message.error('营业执照只能有一张，你可以先删除在进行添加')
    }
  }
}
</script>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow{
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left:20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form{
          display: flex;
          flex-wrap: wrap;
          .el-form-item{
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
